#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the version 3 of the GNU Lesser General Public License
#   as published by the Free Software Foundation.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) NEC Deutschland GmbH, NEC HPC Europe
#
# $Id$

import logging
from cStringIO import StringIO

from aggmon.importer import Importer, ImporterComponent
from basic_types.metric import Metric
from aggmon.metric_containers.nagios_status_log.nagios_status_log_metriccontainer import NagiosStatusLogMetricContainer
from urlparse import urlparse
try:
    from paramiko import SSHClient, AutoAddPolicy
except:
    print "'paramiko' module not found, 'ssh' schema won't work for for nagios status log importer!"


# Constants
NAGIOS_STATUS_PATH = "/var/cache/nagios3/status.dat"
#NAGIOS_STATUS_PATH_V2 = "/var/log/nagios/status.log"
NAGIOS_STATUS_VALUE = [ "OK", "WARNING", "CRITICAL", "UNKNOWN" ]


__all__ = ["NagiosStatusLogImporter", "NagiosStatusLogImporterComponent"]


# Helper function
def parseURL( url ):
    if not "://" in url:
        url = "telnet://" + url
    parsed_url = urlparse( url )
    user_name = parsed_url.username
    password = parsed_url.password
    if password == "":
        password = None
    host_name = parsed_url.hostname
    port = parsed_url.port
    if port == 0 or port is None:
        port = 22   # expect this is ssh
    path = parsed_url.path
    scheme = parsed_url.scheme
    if scheme is not None and path is not None:
        return [scheme, user_name, password, host_name, path, port]
    else:
        raise ValueError, "invalid URL: " + url


class NagiosStatusLogImporter(Importer):
    ## Create Nagios status log importer instance.
    # @param url: URL of file containing nagios status log
    # @return nothing
    def __init__( self, url="", group_only=False, **kwds ):
        scheme, user_name, password, host_name, path, port = parseURL( url )
        Importer.__init__( self, **kwds )
        self._group_only = group_only
        self._ssh_client = None
        self._scheme = scheme
        self._user_name = user_name
        self._password = password
        self._host_name = host_name or "localhost"
        self._path = path or NAGIOS_STATUS_PATH
        self._port = port or 22
        self.metriccontainer = NagiosStatusLogMetricContainer( timeout=60 )

    def _parseNagiosStatusLog( self, __buffer ):
        objects = []
        for line in StringIO( __buffer ).readlines():
            line = line.strip()
            if line.endswith( "{" ):
                objects.append( ( line.split( " " )[0], {} ) )
            elif len( line ) > 0:
                try:
                    key_value = line.split( "=", 1 )
                    if len( key_value ) == 2:
                        key, value = key_value
                        objects[-1][1][key] = value
                except:
                    logging.warn( "Problem with Nagios log: '%s'" % line )

        source = "nagios"
        for object_type, __object in objects:
            if object_type.startswith( "service" ) or object_type.startswith( "host" ):
                try:
                    current_state = int( __object["current_state"] )
                    host_name = __object["host_name"].split(".")[0]
                    if object_type.startswith( "host" ):
                        check = __object["check_command"]
                        if check.startswith( "check-" ) and check.endswith( "-alive" ):
                            name = check.split( "-" )[1] + "_state"
                        else:
                            name = "host_state"
                    else:
                        name = __object["service_description"].replace( " ", "_" )
                    if current_state < 0 or current_state > 3:
                        logging.error( "Wrong state in nagios: %s" % str(current_state) )
                        continue
                    value = NAGIOS_STATUS_VALUE[current_state]
                    time = long( __object["last_check"] )
                    output = __object["plugin_output"]
                except KeyError:
                    continue
                if not self._group_only or (self._group_only and self.getHierarchy().in_own_groups( self._host_name ) ):
                    metric = Metric( name, source, time=time, host=host_name, value=value, output=output )
                    if self.metriccontainer.isNew( metric ):
                        yield metric

    # opens ssh connection and retrieves file through sftp
    def get_file_by_ssh( self ):
        if self._ssh_client is None:
            client = SSHClient()
            client.load_system_host_keys()
            client.set_missing_host_key_policy( AutoAddPolicy() )
            self._ssh_client = client
        if self._ssh_client.get_transport() is None or \
            not self._ssh_client.get_transport().is_authenticated():
            try:
                self._ssh_client.connect( self._host_name, port=self._port,
                                          username=self._user_name, password=self._password, timeout=15 )
            except Exception, e:
                logging.error( "ssh connection to %s failed" % self._host_name )
                raise e
            self._ssh_client.get_transport().set_keepalive( 10 )
        sftp = self._ssh_client.open_sftp()
        f = sftp.open( self._path )
        __buffer = f.read()
        sftp.close()
        return __buffer

    def get_local_file( self ):
        f = open( self._path )
        __buffer = f.read()
        f.close()
        return __buffer

    def poll( self ):
        if self._scheme == "ssh":
            __buffer = self.get_file_by_ssh()
        elif self._scheme == "file":
            __buffer = self.get_local_file()
        else:
            raise ValueError, "Unsupported scheme: " + self._scheme
        for metric in self._parseNagiosStatusLog( __buffer ):
            yield metric


class NagiosStatusLogImporterComponent(ImporterComponent):
    def __init__( self, *args, **kwds ):
        ImporterComponent.__init__( self, *args, **kwds)
        self.allowed_kwds.extend( ["url", "group_only"] )

    def instantiate( self, *args, **kwds ):
        self.instance = None
        try:
            logging.debug( "instantiating: %s" % self.name )
            self.instance = NagiosStatusLogImporter( *args, **kwds )
        except Exception, e:
            raise e
